import { createSlice } from "@reduxjs/toolkit";
import { getTokenAPI,getUserInfoAPI } from "@/api/user";
import {setTokenLocalStorage,getTokenLocalStorage} from '@/utils/storage'

const userStore=createSlice({
  name:'user',
  initialState:{
    token:getTokenLocalStorage() ||'',
    userInfo:{}
  },
  reducers:{
    setToken(state,action){
      state.token=action.payload
      setTokenLocalStorage(action.payload)
    },
    setUserInfo(state,action){
      state.userInfo=action.payload
    },
    removeUserInfo(state){
      state.userInfo={}
    }
  }
})

//获取token
const getToken=(data)=>{
  return async (dispatch)=>{
    const res=await getTokenAPI(data)
    dispatch(setToken(res.data.token))
  }
}

//获取用户信息
const getUserInfo=()=>{
  return async(dispatch)=>{
    const res=await getUserInfoAPI()
    dispatch(setUserInfo(res.data))
  }
}

const {setToken,setUserInfo,removeUserInfo}=userStore.actions

const reducer=userStore.reducer
export {setToken,getToken,getUserInfo,removeUserInfo}
export default reducer